package org.jeecg.activiti.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.jeecg.activiti.entity.ActKAppendFormData;
import org.jeecg.activiti.service.IActKAppendFormDataService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO 流程节点附加表单数据controller
 *
 * @author dousw
 * @version 1.0
 * @date 2020/10/10 10:45
 */
@RestController
@RequestMapping("/activiti/appendFormData")
@Api(tags = "流程节点附加表单数据管理")
public class ActKAppendFormDataController {

    @Autowired
    private IActKAppendFormDataService iActKAppendFormDataService;

    @GetMapping("/getActKAppendFormData")
    @ApiOperation(value = "查询流程节点附加表单数据", notes = "查询流程节点附加表单数据")
    public Result<Object> getActKAppendFormData(@ApiParam("流程实例id") @RequestParam String processInstanceId,
                                    @ApiParam("流程节点id") @RequestParam String nodeId){
        List<ActKAppendFormData> actKAppendFormDatas = iActKAppendFormDataService.list(new QueryWrapper<ActKAppendFormData>()
                .eq("process_instance_id", processInstanceId)
                .eq("node_id", nodeId)
                .orderByDesc("create_time")
        		);

        // 一个任务节点如果查到多个附加表单数据，取最新的一个
        if (!CollectionUtils.isEmpty(actKAppendFormDatas)) {
            ActKAppendFormData actKAppendFormData = actKAppendFormDatas.get(0);
            return Result.OK(actKAppendFormData);
        }

        return Result.error("无附加表单数据");
    }

    /**
     * 保存/修改流程节点附加表单数据
     * @return
     */
    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "保存/修改流程节点附加表单数据", notes = "保存/修改流程节点附加表单数据")
    public Result<Object> saveOrUpdate(@RequestBody ActKAppendFormData actKAppendFormData){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        actKAppendFormData.setUsername(sysUser.getUsername());
        actKAppendFormData.setCreateBy(sysUser.getUsername());
        actKAppendFormData.setCreateTime(new Date());
        iActKAppendFormDataService.save(actKAppendFormData);

        return Result.OK();
    }
}
